import { message } from 'antd';

/**
 * Http工具类
 */
class Http {

    static ajax(url, params, method) {

        let config = {
            method: method, 
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            cache: 'no-store'
        };

        let search = '';
        if (params) {
            for (var p in params) {
                if (params[p] == null || typeof(params[p]) === 'undefined') {
                    delete params[p];
                } else {
                    search += p + '=' + encodeURIComponent(params[p]) + '&';
                }
            }

            if (search) {
                search = search.substr(0, search.length - 1);

                if (method.toLocaleLowerCase() === 'get') {
                    if (url.indexOf('?') > 0) {
                        url += '&' + search;
                    } else {
                        url += '?' + search;
                    }
                } else {
                    config.body = search;
                }
            }
        }

        return new Promise(function (resolve, reject) {
            fetch(url, config).then(function (response) {
                return response.json();
            }).then(function (data) {
                if (data.code === '0000') {
                    resolve(data);
                } else if (data.code === '9993') {
                    message.error('未登录,' + data.msg);
                    reject(null, data);
                    window.location = '/login';
                } else {
                    message.error(data.msg);
                    reject(null, data);
                }
            }).catch(function (e) {
                reject(e);
            });
        });
    }

    /**
     * 发起Post请求
     * 
     * @param {String} url 请求地址
     * @param {object} params 请求参数
     */
    static Post(url, params) {
        return Http.ajax(url, params, 'POST');
    }

    /**
     * 发起Get请求
     * 
     * @param {String} url 请求地址
     * @param {Object} params 请求参数
     */
    static Get(url, params) {
        return Http.ajax(url, params, 'GET');
    }
}

class BeanUtils {

    /**
     * 深层拷贝一个对象
     * @param {*any} src  源对象
     */
    static copy(src) {
        return JSON.parse(JSON.stringify(src));
    }
}

export { Http, BeanUtils };